package win.ganbo.softwareFive.service.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import win.ganbo.softwareFive.service.IBaseService;

@Service
@SuppressWarnings("all")
public abstract class BaseServiceImpl<T> implements IBaseService<T> {

    protected Logger         logger = Logger.getLogger(getClass());

    @Autowired
    protected SessionFactory sf;

    protected Class<T>       clazz;

    public BaseServiceImpl() {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) type;
            clazz = (Class<T>) ptype.getActualTypeArguments()[0];
            //            System.out.println("entityClass===>" + clazz);
        }
    }

    public Session getSession() {
        return sf.getCurrentSession();
    }

    public void save(T t) {
        getSession().save(t);
    }

    @Override
    public void saveOrUpdate(T t) {
        getSession().saveOrUpdate(t);
    }

    public void delete(Serializable id) {
        T t = get(id);
        if (t != null) {
            getSession().delete(t);
        }
    }

    @Override
    public void deleteAll() {
        getSession().createQuery("DELETE " + clazz.getName()).executeUpdate();
    }

    public void update(T t) {
        getSession().update(t);
    }

    public T get(Serializable id) {
        return (T) getSession().get(clazz, id);
    }

    public List<T> getAll() {
        return getSession().createQuery("FROM " + clazz.getName()).list();
    }

    public List findByHql(String hql, Object... params) {
        Query query = getSession().createQuery(hql);
        if (params == null)
            return null;
        int index = 0;
        if (params != null) {
            for (Object o : params) {
                query.setParameter(index++, o);
            }
        }
        return query.list();
    }

    public Object getUniqueResult(String hql, Object... params) {
        Query query = getSession().createQuery(hql);
        int index = 0;
        if (params != null) {
            for (Object o : params) {
                query.setParameter(index++, o);
            }
        }
        return query.uniqueResult();
    }

    public List<T> findAll() {
        return getSession().createQuery("FROM " + clazz.getName()).list();
    }

    //构建hibernate查询参数
    public Query buildParams(Query query, Object... params) {
        int index = 0;
        for (Object param : params) {
            query.setParameter(index++, param);
        }
        return query;
    }

}
